/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufpe.cin.dmo4.middleware.server;

import br.ufpe.cin.dmo4.middleware.io.SocketChannelHandler;
import java.io.IOException;
import java.nio.channels.SocketChannel;

/**
 *
 * @author Danilo
 */
public class ClientConnection implements Runnable {

    private final SocketChannel socketChannel;
    private SocketChannelHandler handler;
    private volatile byte[] response;
    private final ServerHandlerListener listener;

    public ClientConnection(SocketChannel socket, ServerHandlerListener listener) {
        this.socketChannel = socket;
        this.listener = listener;
        this.handler = new SocketChannelHandler(socket);
    }

    @Override
    public void run() {
        try {
            byte[] message = handler.getBytes();
            
            listener.receiveMessage(message, this);

            while (response == null) {               
            }

            handler.writeBytes(response);

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void send(byte[] bytes) {
        response = bytes;
    }

    

}
